//
//  ST_NearbyST_LiveBeautyController.swift
//  btvideo
//
//  Created by mac on 2021/5/7.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import MJRefresh
import SwiftyUserDefaults

class ST_NearbyST_LiveBeautyController: UIViewController {
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
         
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            self?.currentPage = 0
            self?.request_data()
        })
        
        binding()
        
        
        
    }
    
    private func binding(){
        
        NotificationCenter.default.rx.notification(ST_LiveBeautyWidget.delete_live_queue_notification, object: nil).withUnretained(self).subscribe(onNext: { own,n in
            
            own.delete_notification(noti: n)
            
        }).disposed(by: rx.disposeBag)
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().withUnretained(self).subscribe(onNext: { own,f in
            print("SCComponets.login_status_did_changed_observable()")
            if f == true{
                own.currentPage = 0
                own.request_data()
            }else{
                own.data_array.removeAll()
                own.collectionView.reloadData()
            }
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    @objc fileprivate func delete_notification(noti:Notification){
        
        let json = JSON(noti.userInfo ?? "")
        
        let accid = json["accid"].stringValue
        
        guard let removeIndex = data_array.firstIndex(where:({$0.accid == accid})) else{
            return
        }
        
        let index = Int(removeIndex.uInt)
        
        collectionView.performBatchUpdates({
            
            data_array.remove(at: index)
            
            collectionView.deleteItems(at: [IndexPath(row: index, section: 0)])
            
        }) { (f) in
            
            if self.data_array.count < 1{
                
                self.collectionView.reloadData()
                
            }
            
            print("切换 显示 完毕")
            
        }
        
    }
   
  
    fileprivate var first = true
    
    fileprivate var currentPage = 0
    
    fileprivate func request_data(){
        
        currentPage += 1
        
        let param = ["page":currentPage,"size":20]
        
        
        JVrequest(api,parameters: param) { (json) in
            
            self.first = false
            
            let array = json["data"].arrayValue.map({ST_LiveBeautyCellModel.init(fromJson: $0)})
            
            if self.currentPage == 1{
                self.data_array = array
            }else{
                self.data_array += array
            }
            
            self.collectionView.reloadData()
            
            
            self.load_more_option_style(tableView: self.collectionView, count: array.count, pageSize: 20) {[weak self] in
                
                self?.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                    
                    self?.request_data()
                })
            }
            
            self.collectionView.mj_footer?.endRefreshing()
            
            self.collectionView.mj_header?.endRefreshing()
            
        } failure: { (code, err) in
            
            self.toast(text: err)
            
            self.collectionView.mj_footer?.endRefreshing()
            
            self.collectionView.mj_header?.endRefreshing()
            
        }
        
    }
    
//    MARK: - Properties
    var api = ""
    
    
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        controlLayout.minimumLineSpacing = 1
        controlLayout.minimumInteritemSpacing = 1
        controlLayout.sectionInset = UIEdgeInsets.init(top: 10, left: 11, bottom: BTSafeAreaBottom + 49, right: 11)
        let w = (ScreenWidth - 1 - 11*2)/2
        controlLayout.itemSize = CGSize.init(width: w, height: w/168.0*190+103+4*2)
        
//        controlLayout.headerReferenceSize = CGSize(width: ScreenWidth, height: 19+80)
        
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_LiveBeautyCell.self)
        
        
        control.emptyDataSetSource = self
        
        control.emptyDataSetDelegate = self
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.backgroundColor = UIColor.white
        control.alwaysBounceVertical = true
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    
    
    fileprivate(set) lazy var data_array = [ST_LiveBeautyCellModel]()
    
    
}


//MARK: -
extension ST_NearbyST_LiveBeautyController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_LiveBeautyCell.self, for: indexPath)
        
        cell.model = data_array[safe:indexPath.row]
        
        return cell
    }
    
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        

        guard let model = data_array[safe:indexPath.row] else { return  }
        
        invite_chat_action(cellModel: model)
        
    }
}




extension ST_NearbyST_LiveBeautyController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
    
    func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool {
        return true
    }
    
    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool {
        
        if first{
            self.first = false
            return false
        }else{
            return true
        }
    }
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        
        var str = "当前没有小姐姐接受速配邀请哦\n晚点再来看看"
        
        if let user = ST_BTUserInfoManager.shared.current_account_info?.userinfo ,user.sex == .female {
            str = "小哥哥们太腼腆，主动去邀约心仪\n的小哥通话吧"
        }
        
        let attrString = NSMutableAttributedString(string: str)
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16),.foregroundColor: UIColor.init(hex: 0xCDD1DB)!]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        
        return ST_ImageUtils.imageName("首页_img_gift_empty")
    }
}


extension ST_NearbyST_LiveBeautyController{
    
    @objc fileprivate func invite_chat_action(cellModel:ST_LiveBeautyCellModel){
        
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
            return
        }
        
        
        let isVideo:Bool = cellModel.type == 2
        
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == cellModel.sex,let str = SCComponets.rich_text_storage_component.json["limitations"]["cot"].string,str.count > 2{

            self.toast(text: str)

            return
        }
        
        
        ST_MediaChatDispatcher.shared.inviteChat(sessionId: cellModel.accid, isVideo: isVideo,inviteDistract: "upLiveWall")
        
    }
    
}
